<template>
  <div class="chat-view">
    <!-- 顶部导航 -->
    <div class="chat-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <span class="name">{{ username }}</span>
      <div class="actions">
        <van-icon name="phone" class="action-icon" @click="call" />
      </div>
    </div>

    <!-- 聊天内容 -->
    <div class="chat-messages" ref="listRef">
      <template v-for="(message, index) in chatMessages" :key="index">
        <!-- 时间分隔（仿微信） -->
        <div v-if="shouldShowTime(index)" class="time-sep">
          {{ formatTime(message.ts) }}
        </div>

        <!-- 消息气泡 -->
        <div :class="['message-item', message.isMine ? 'my-message' : 'friend-message']">
          <img class="avatar" :src="message.avatar" />
          <div class="message-bubble">
            <p v-if="message.content">{{ message.content }}</p>
            <div v-if="message.images && message.images.length" class="message-images">
              <img v-for="(img, imgIndex) in message.images" :key="imgIndex" :src="img" class="message-image" />
            </div>
          </div>
        </div>
      </template>
    </div>

    <!-- 底部输入区域 -->
    <div class="bottom-area bump-up">
      <div class="chat-input-area">
        <div class="input-container">
          <!-- 语音按钮 -->
          <button class="voice-icon-btn" @click="startVoiceRecord" title="语音">
            <van-icon name="volume-o" size="20" color="#666" />
          </button>

          <!-- 输入框 -->
          <van-field
            ref="messageInput"
            v-model="newMessage"
            placeholder="输入消息..."
            clearable
            class="message-input"
            :style="{ '--van-field-padding-horizontal': '50px', '--van-field-height': '0px' }"
            @keyup.enter="sendMessage"
          />

          <!-- 表情按钮 -->
          <button class="icon-btn emoji-btn" @click="toggleEmoji" title="表情">
            <van-icon name="smile" size="30" color="#666" />
          </button>

          <!-- 更多（无内容时显示） -->
          <button class="icon-btn plus-btn" @click="toggleMenu" title="更多" v-if="!newMessage.trim()">
            <van-icon name="plus" size="20" color="#666" />
          </button>

          <!-- 发送箭头（有内容时显示） -->
          <button class="send-btn" @click="sendMessage" v-if="newMessage.trim()" title="发送">
            <van-icon name="arrow" size="18" />
          </button>
        </div>
      </div>

      <!-- 功能面板 -->
      <transition name="slide-up">
        <div v-if="showMenu" class="menu-popup">
          <div class="menu-grid">
            <div class="menu-item" @click="openAlbum">
              <van-icon name="photo-o" size="24" />
              <span>相册</span>
            </div>
            <div class="menu-item" @click="startVideo">
              <van-icon name="video-o" size="24" />
              <span>视频通话</span>
            </div>
            <div class="menu-item" @click="openGift">
              <van-icon name="gift" size="24" />
              <span>礼物</span>
            </div>
            <div class="menu-item" @click="openPet">
              <van-icon name="add-o" size="24" />
              <span>召唤宠物</span>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Field as VanField } from 'vant'

const route = useRoute()
const router = useRouter()
const username = route.params.username as string

// 头像（按你的项目路径替换）
const MY_AVATAR = '/public/chat/role_zhujue_head.png'
const HUMAN_AVA = '/public/chat/role_hushinv_head.png'
const PET_AVA   = '/public/chat/pet_nvhai_head.png'

// 好友当前头像（召唤宠物后切为宠物）
const friendAvatar = ref(HUMAN_AVA)

/** ===== 消息类型：含 ts、showTime ===== */
type Msg = {
  content?: string
  isMine: boolean
  avatar: string
  images?: string[]
  ts: number
  showTime?: boolean
}

const now = () => Date.now()
const todayAt = (h: number, m: number) => {
  const d = new Date()
  d.setHours(h, m, 0, 0)
  return d.getTime()
}
const FIXED_1005 = todayAt(10, 5)

/** 初始消息 */
const chatMessages = ref<Msg[]>([
  {
    content: '你说得有道理，我是要尝试寻找人生的副线了。',
    isMine: false,
    avatar: friendAvatar.value,
    ts: now() - 100 * 60 * 1000,
    showTime: false, // 最顶上不显示时间
  },
  {
    content: '在吗？最近找到了吗？',
    isMine: true,
    avatar: MY_AVATAR,
    ts: now()- 5 * 60 * 1000,

    showTime: true,  // 从这里开始显示时间
  },
  {
    content: '看你日记好像心情不错',
    isMine: true,
    avatar: MY_AVATAR,
    ts:  now()- 5 * 60 * 1000,
  },
])

const newMessage = ref('')
const showMenu = ref(false)
const messageInput = ref<InstanceType<typeof VanField> | null>(null)
const listRef = ref<HTMLElement | null>(null)

/** 工具：滚动到底部 */
const scrollToBottom = () => nextTick(() => {
  const el = listRef.value
  if (el) el.scrollTop = el.scrollHeight
})
const focusInput = () => nextTick(() => (messageInput.value as any)?.focus?.())

/** ===== 时间显示（仿微信） ===== */
const GAP_MS = 5 * 60 * 1000
const shouldShowTime = (index: number) => {
  const cur = chatMessages.value[index]
  if (!cur) return false
  if (cur.showTime === true) return true
  if (cur.showTime === false) return false
  if (index === 0) return false
  const prevTs = chatMessages.value[index - 1]?.ts ?? 0
  return cur.ts - prevTs >= GAP_MS
}
const formatTime = (ts: number) => {
  const d = new Date(ts)
  const hh = String(d.getHours()).padStart(2, '0')
  const mm = String(d.getMinutes()).padStart(2, '0')
  return `${hh}:${mm}`
}

/** ===== 消息队列：按固定间隔逐条弹出 ===== */
const enqueueMessages = (items: Omit<Msg, 'ts'>[], interval = 1000) => {
  let i = 0
  const start = now()
  const tick = () => {
    if (i >= items.length) return
    const base = items[i]
    chatMessages.value.push({
      ...base,
      ts: start + i * interval,
    })
    i++
    scrollToBottom()
    if (i < items.length) setTimeout(tick, interval)
  }
  tick()
}

/** 发送消息（对方 1s 后回复一条） */
const sendMessage = () => {
  const text = newMessage.value.trim()
  if (!text) return

  chatMessages.value.push({
    content: text,
    isMine: true,
    avatar: MY_AVATAR,
    ts: now(),
  })
  newMessage.value = ''
  showMenu.value = false
  scrollToBottom()

  // 模拟对方 1s 后回复
  setTimeout(() => {
    const replies = ['哈哈，确实很有趣～', '我也这么觉得！', '你说得对呀～', '是呢，特别精彩！']
    const randomReply = replies[Math.floor(Math.random() * replies.length)]
    enqueueMessages([
      { content: randomReply, isMine: false, avatar: friendAvatar.value }
    ], 1000)
  }, 1000)
}

/** 功能面板 / 语音 / 其它 */
const toggleMenu = () => (showMenu.value = !showMenu.value)
const startVoiceRecord = () => alert('开始语音输入（可替换为真实录音逻辑）')
const openAlbum = () => { alert('打开相册'); showMenu.value = false }
const startVideo = () => { alert('开始视频通话'); showMenu.value = false }
const openGift  = () => { alert('打开礼物'); showMenu.value = false }

/** —— 召唤宠物：按 1s 间隔依次弹出整段对话 —— */
const summonLock = ref(false)
const openPet = () => {
  if (summonLock.value) return
  summonLock.value = true
  showMenu.value = false

  // 我方先发
  chatMessages.value.push({
    content: '@宠物 出来',
    isMine: true,
    avatar: MY_AVATAR,
    ts: now(),
  })
  scrollToBottom()

  // 切换好友头像为宠物
  friendAvatar.value = PET_AVA

  // 按 1s 间隔逐条弹出
  setTimeout(() => {
    enqueueMessages(
      [
        { content: '你好，想聊些啥？',              isMine: false, avatar: friendAvatar.value },
        { content: '你家主人找副线有什么进展',       isMine: true,  avatar: MY_AVATAR },
        { content: '她跟我说了',                    isMine: false, avatar: friendAvatar.value },
        { content: '所以',                          isMine: true,  avatar: MY_AVATAR },
        { content: '我得替她保密，诶嘿',            isMine: false, avatar: friendAvatar.value },
        { content: '……',                           isMine: true,  avatar: MY_AVATAR },
      ],
      1000 // 间隔 1s
    )
    // 放开锁（不用等全部结束也行）
    setTimeout(() => { summonLock.value = false; focusInput() }, 200)
  }, 800)
}

/** 顶部导航 */
const goBack = () => router.back()
const call = () => alert('拨打电话')
const toggleEmoji = () => alert('切换表情')
</script>

<style scoped>
.chat-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  background-color: #fff;
}

/* 顶部 */
.chat-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 8px 16px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
  flex-shrink: 0;
  height: 55px;
}
.back-icon, .action-icon { font-size: 22px; cursor: pointer; }
.name { flex: 1; text-align: center; font-size: 18px; font-weight: bold; margin: 0 40px; }
.actions { display: flex; gap: 12px; }

/* 列表 */
.chat-messages {
  height: 78vh;
  padding: 16px;
  overflow-y: auto;
  text-align: center;
}
.time-sep{
  display: inline-block;
  margin: 10px auto 12px;
  padding: 4px 10px;
  background: #f0f0f0;
  color: #8c8c8c;
  font-size: 12px;
  border-radius: 10px;
  line-height: 1;
}
.message-item { display: flex; margin-bottom: 12px; align-items: flex-start; text-align: left; }
.avatar { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; margin-right: 8px; }
.friend-message .message-bubble {
  background: #f5f5f5; padding: 10px 14px; border-radius: 18px; border-top-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); font-size: 14px; max-width: 70%;
}
.my-message { align-self: flex-end; flex-direction: row-reverse; }
.my-message .avatar { margin-right: 0; margin-left: 8px; }
.my-message .message-bubble {
  background: #d4f1f4; padding: 10px 14px; border-radius: 18px; border-top-right-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); font-size: 14px; max-width: 70%;
}
.message-images { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 4px; }
.message-image { width: 80px; height: 80px; object-fit: cover; border-radius: 4px; }

/* 底部输入区域 */
.bottom-area {
  border-top: 1px solid #eee;
  background: #fff;
  flex-shrink: 0;
  transform: translateY(-1px);
  transition: transform .25s ease;
}
.chat-input-area { padding: 8px 10px; display: flex; align-items: flex-start; }
.input-container { display: flex; align-items: flex-start; width: 100%; gap: 6px; }

/* 按钮 */
.voice-icon-btn, .icon-btn {
  width: 29px; height: 29px; border: 1px solid #ddd; border-radius: 50%;
  display: inline-flex; align-items: center; justify-content: center; cursor: pointer; background: #fff;
}
.voice-icon-btn:hover, .icon-btn:hover { background-color: #f5f5f5; }

/* 输入框 */
.message-input {
  flex: 1; display: flex; align-items: center;
  height: 30px !important; padding: 10px; border: 1px solid #ddd; border-radius: 12px;
}

/* 发送箭头按钮 */
.send-btn {
  height: 30px; background-color: #fff; color:#333; border: none; border-radius: 12px;
  padding: 0 7px; cursor: pointer; flex-shrink: 0; font-size: 15px;
  display: flex; align-items: center; justify-content: center;
  box-shadow: 0 0 4px rgba(0,0,0,.1);
}

/* 功能面板 */
.menu-popup {
  background: #f9f9f9;
  padding: 12px 20px;
  border-top: 1px solid #ddd;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 55px;
}
.menu-grid {
  display: grid; grid-template-columns: repeat(4, 1fr);
  gap: 20px 0; justify-items: center;
}
.menu-item {
  width: 64px; height: 64px; background: #fff; border-radius: 16px;
  display: flex; flex-direction: column; align-items: center; justify-content: center;
  cursor: pointer; box-shadow: 0 0 4px rgba(0,0,0,.1); transition: background-color .2s;
  font-size: 12px; color: #333;
}
.menu-item:hover { background-color: #e6f7ff; }
.menu-item van-icon { margin-bottom: 6px; }

.slide-up-enter-active, .slide-up-leave-active { transition: all .3s ease; }
.slide-up-enter-from, .slide-up-leave-to { transform: translateY(100%); opacity: 0; }

/* Vant 微调 */
::v-deep(.van-icon){ display:inline-block!important; }
::v-deep(.van-field__control){ padding:0!important; font-size:16px!important; line-height:40px!important; }
::v-deep(.van-field__placeholder){ font-size:16px!important; }
::v-deep(.van-field__wrap){ padding:0!important; border:none!important; }
</style>